package com.xgd.phylw.dispathcer;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * Author:flyyoung
 * Date:2021/5/24 9:37
 * Desc:
 **/
@Controller
public class CheckCodeServlet extends HttpServlet {
    @GetMapping("CheckCodeServlet")
    public void checkCode(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {

        //创建宽100px,高50px,的一张rgb图片
        BufferedImage img = new BufferedImage(80,40,BufferedImage.TYPE_INT_RGB);
        //获取该图片的画笔
        Graphics hb = img.getGraphics();
        hb.setColor(Color.orange);
        hb.fillRect(0, 0, 80, 48);
        hb.setColor(Color.gray);
        hb.drawRect(0, 0, 78, 38);

        String sjs = "ASDFGHJKLPOIUYTREWQZXCVBNMasdfghjklqwertyuiopmnbvcxz1234567890";
        Random rd = new Random();
        String code="";
        for (int i = 0; i < 4; i++) {
            if(i%2==0) {
                hb.setColor(Color.MAGENTA);
            }else if(i%2==1) {
                hb.setColor(Color.red);
            }else {
                hb.setColor(Color.blue);
            }
            int num = rd.nextInt(sjs.length());
            char sz = sjs.charAt(num);
            code+=sz;
            hb.drawString(sz+"", 10+i*20,30);
        }
        session.setAttribute("yzm",code);
        for (int i = 0; i < 6; i++) {
            if(i==1 || i==3) {
                hb.setColor(Color.blue);
            }else if(i==2 || i==4) {
                hb.setColor(Color.cyan);
            }else {
                hb.setColor(Color.darkGray);
            }
            hb.drawLine(rd.nextInt(70), rd.nextInt(30), rd.nextInt(70), rd.nextInt(30));
        }
        ImageIO.write(img,"jpg",response.getOutputStream());
    }
}
